﻿using B.S.XZYData.Api.Read.Application.Command.Permission;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;

namespace B.S.XZYData.Api.Read.Application.Handler.Permission
{
    /// <summary>
    /// 权限列表实现层
    /// </summary>
    public class GetPermissionHandler : IRequestHandler<GetPermissionCommand, ApiPageing<PermissionModel>>
    {
        private readonly IBaseRepository<PermissionModel> permissionRepo;

        public GetPermissionHandler(IBaseRepository<PermissionModel> permissionRepo)
        {
            this.permissionRepo = permissionRepo;
        }
        /// <summary>
        /// 查询权限列表方法
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回查询到的权限列表</returns>
        public Task<ApiPageing<PermissionModel>> Handle(GetPermissionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var res = new ApiPageing<PermissionModel>();
                var permission = permissionRepo.GetAll().Where(x => !x.IsDeleted);
                if (!string.IsNullOrEmpty(request.PermissionName))
                {
                    permission = permission.Where(x => x.PermissionName.Contains(request.PermissionName));
                }
                
                // 获取所有权限数据用于构建父级权限名称映射
                var allPermissions = permissionRepo.GetAll().Where(x => !x.IsDeleted).ToList();
                var permissionMap = allPermissions.ToDictionary(x => x.Id, x => x.PermissionName);
                
                // 分页查询
                res.TotaCount = permission.Count();
                res.TotaPage = (int)Math.Ceiling(res.TotaCount * 1.0 / request.Size);
                var pageData = permission.OrderByDescending(x => x.Number).Skip((request.Index - 1) * request.Size).Take(request.Size).ToList();
                
                // 设置父级权限名称
                foreach (var item in pageData)
                {
                    if (item.ParentId > 0 && permissionMap.ContainsKey(item.ParentId))
                    {
                        item.ParentName = permissionMap[item.ParentId];
                    }
                    else
                    {
                        item.ParentName = string.Empty;
                    }
                }
                
                res.PageData = pageData;
                res.Msg = "查询权限列表成功!";
                res.Code = ApiEnum.Success;
                return Task.FromResult(res);
            }
            catch (Exception ex)
            {
                var res = new ApiPageing<PermissionModel>();
                res.Msg = "查询权限列表发生异常" + ex.Message;
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
                throw;
            }
        }
    }
}
